const http = require('http')
const fs = require('fs')

var userList = []

function getData(str) {
    var arr = str.split('&')
    var obj = {}
    for (var i = 0; i < arr.length; i++) {
        var childArr = arr[i].split('=')
        obj[childArr[0]] = childArr[1]

    }
    return obj
}

http.createServer((req, res) => {
    var urlObj = new URL(req.url, 'http://localhost:8081')
    var pathName = urlObj.pathname
    // 响应提交表单到页面
    if (pathName == '/') {
        var fileContent = fs.readFileSync('./post.html')
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
        res.write(fileContent)
        res.end()
    }
    // 响应list.html页面到浏览器
    else if (pathName == '/list') {
        var fileContent = fs.readFileSync('./list.html')
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
        res.write(fileContent)
        res.end()
    }
    // 响应userList数据到客户端
    else if (pathName == '/getlist') {
        var userStr = JSON.stringify(userList)
        res.writeHead(200, { "Content-Type": 'text/plain' })
        res.end(userStr)
    }
    // 做表单数据的接收，存储到userList中
    else if (pathName == '/save') {
        var str = ''
        req.on('data', (chunk) => {
            str += chunk
        })
        req.on('end', (chunk) => {
            var postObj = getData(str)
            userList.push(postObj)
            res.end('submit success')
        })
    }
    // 删除数据，接收请求/del?deluser=zhangsan，根据username从userList里面将该数据删除
    else if (pathName == '/del') {
        var delUser = urlObj.searchParams.get('deluser')

        for (var i = 0; i < userList.length; i++) {
            if (userList[i]['username'] == delUser) {
                userList.splice(i, 1)
                res.end('deleted')
                return;
            }
        }
    }
}).listen(8081)